<?php

namespace Sharks\Core\LifeCycle;

use Sharks\Core\Support\Bag\ParameterBag;

abstract class ActionParamResolver {

	private static $resolvers;
    private static $paramContainer;

	public static function register(ActionParamResolver $resolver) {

		if (is_null(self::$resolvers)) {
			self::$resolvers = array();
		}
		self::$resolvers[] = $resolver;
	}

	/**
	 * 通过参数名称或参数类型来判断应该解析的参数值
	 * 当匹配到值时就返回该值，因此当有同一类型或名称的判断时，不能严格控制匹配顺序与返回的解析值‘
	 * 当无匹配值时，返回 null
	 * @param $paramName
	 * @param $paramType
	 */
	public static function get($paramName, $paramType) {
		if (is_null(self::$resolvers)) {
			return null;
		}
		if (is_null(self::$paramContainer)) {
		    self::$paramContainer = new ParameterBag();
        }

        // 如果已经加载过，则返回已加载的参数
        if (self::$paramContainer->has($paramName)) {
            return self::$paramContainer->get($paramName);
        }
		foreach (self::$resolvers as $resolver) {
			$param = $resolver->resolve($paramName, $paramType);
			if (!is_null($param)) {
			    self::$paramContainer->put($paramName, $param);
				return $param;
			}
		}
		return null;
	}

	abstract function resolve($paramName, $paramType);
}